package org.example.aienglishapp.service.progress;


import org.example.aienglishapp.entity.progress.Course;
import org.example.aienglishapp.mapper.progress.CourseMapper;
import org.example.aienglishapp.mapper.progress.UserCoursesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    private final CourseMapper courseMapper;
    private final UserCoursesMapper userCoursesMapper;

    @Autowired
    public CourseServiceImpl(CourseMapper courseMapper, UserCoursesMapper userCoursesMapper){
        this.courseMapper = courseMapper;
        this.userCoursesMapper = userCoursesMapper;
    }

    @Override
    public List<Course> getAvailableCourses(Long userId) {
        return courseMapper.getAvailableCourses(userId);
    }

    @Override
    public List<Course> getEnrolledCourses(Long userId) {
        return courseMapper.getEnrolledCourses(userId);
    }

    @Override
    public void enrollCourse(Long userId, Long courseId) throws Exception {
        // 检查用户是否已经选课
        List<Course> enrolledCourses = courseMapper.getEnrolledCourses(userId);
        boolean alreadyEnrolled = enrolledCourses.stream()
                .anyMatch(course -> course.getCourseId().equals(courseId));
        if(alreadyEnrolled){
            throw new Exception("用户已选修该课程");
        }
        // 选课
        userCoursesMapper.enrollCourse(userId, courseId);
    }

    @Override
    public void deleteEnrollment(Long userId, Long courseId) throws Exception {
        if (!courseMapper.existsByUserIdAndCourseId(userId, courseId)) {
            throw new IllegalArgumentException("选课记录不存在");
        }
        courseMapper.deleteEnrollment(userId, courseId);
    }
    }